package com.zy.orders.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.model.OrderItems;
import com.zy.orders.mapper.OrdersItemsMapper;
import com.zy.web.api.IdGeneratorApi;
import com.zy.web.bean.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: shopping147_cloud
 * @description:
 * @author: zy
 * @create: 2025-08-02 14:22
 */

@Service
public class OrdersItemsServiceImpl extends ServiceImpl<OrdersItemsMapper, OrderItems> implements OrdersItemsService {

    @Autowired
    private IdGeneratorApi idGeneratorApi;


    @Override
    @Transactional
    public boolean saveBatchOrderItems(List<OrderItems> orderItemsList) {
        if (orderItemsList == null || orderItemsList.isEmpty()) {
            return true;
        }
        ResponseResult rr = idGeneratorApi.getBatchIds(orderItemsList.size());
        if( rr.getCode()==0){
            throw new RuntimeException("获取id失败");
        }
        // 关键改动：ids 列表作为局部变量，仅在当前方法调用中有效
        List<Long> ids = (List<Long>) rr.getData();

        if (ids.size() != orderItemsList.size()) {
            throw new RuntimeException("获取的ID数量与订单项数量不匹配");
        }

        // 为每个订单项生成唯一的ID
        List<OrderItems> itemsWithIds = orderItemsList.stream().map(item -> {
            item.setId(ids.remove(0));
            return item;
        }).collect(Collectors.toList());

        // 使用 MyBatis-Plus 提供的批量插入方法
        return this.saveBatch(itemsWithIds);
    }
}
